package com.xymtop.sqlcater.core.sql.sqlparser.tosql.xmind.parse;

import com.xymtop.sqlcater.core.sql.sqlparser.tosql.entity.sql.InputType;
import com.xymtop.sqlcater.core.sql.sqlparser.tosql.life.BaseNodeBuilder;
import com.xymtop.sqlcater.core.sql.sqlparser.tosql.entity.sql.AppContent;
import com.xymtop.sqlcater.core.sql.sqlparser.tosql.entity.sql.BaseNode;
import lombok.Data;
import org.xmind.core.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Data
public class ParseXmind {

    //解析上下文
    private AppContent appContent;


    public static ParseXmind add(String path){
        ParseXmind parseXmind = new ParseXmind();
        AppContent appContent = new AppContent();
        appContent.setPath(path);
        parseXmind.setAppContent(appContent);

        return parseXmind;
    }

    public AppContent parse( ) throws IOException, CoreException {
        //初始化构造器
        IWorkbookBuilder workbookBuilder = Core.getWorkbookBuilder();

        //从文件中加载
        FileInputStream fileInputStream=new FileInputStream(new File(appContent.getPath()));
        IWorkbook iWorkbook = workbookBuilder.loadFromStream(fileInputStream, ".");

        //加载主表
        ISheet primarySheet = iWorkbook.getPrimarySheet();

        //加载根节点
        ITopic rootTopic = primarySheet.getRootTopic();

        //加载第二层节点
        List<ITopic> allChildren = rootTopic.getAllChildren();
        List<BaseNode> baseNodeList = new ArrayList<>();

        //循环遍历节点
        for(ITopic iTopic : allChildren){
            String name = iTopic.getTitleText();

            //子节点是value
          for(ITopic subTopic :iTopic.getAllChildren()){

              String value = subTopic.getTitleText();


              //构建未解析的基础节点
              BaseNode baseNode = new BaseNode();

              baseNode.setKey(name);
              baseNode.setValue(value);

             baseNodeList.add(baseNode);

          }

        }

        appContent.setBaseNodeList(baseNodeList);
        BaseNodeBuilder baseNodeBuilder = new BaseNodeBuilder();
        baseNodeBuilder.setBaseNodeList(baseNodeList);

        appContent.buildElementList(baseNodeBuilder);

        //来自xmind
        appContent.setInputType(InputType.XMIND);
        return appContent;
    }
}
